package archer.framework.utils;


import archer.framework.core.exception.BaseException;
import jodd.io.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 网络工具类
 *
 * @author christ
 * @date 2015/9/29
 */
public class NetUtils extends NetUtil {

    private static Logger logger = LoggerFactory.getLogger(NetUtils.class);

    /**
     * Returns Local Host IP Address
     *
     * @return local Host IP address
     * @throws UnknownHostException
     * @throws SocketException
     */
    public static String getLocalHostAddress() throws BaseException {
        try {
            return getLocalHost().getHostAddress();
        } catch (Throwable e) {
            logger.error("---------->>获取本机ip地址出错", e);
            return "unknown";
        }
    }

    /**
     * Returns Local Host Name
     *
     * @return local Host Name
     * @throws UnknownHostException
     * @throws SocketException
     */
    public static String getLocalHostName() throws BaseException {
        try {
            return getLocalHost().getHostName();
        } catch (Throwable e) {
            logger.error("---------->>获取本机计算机名出错", e);
            return "unknown";
        }
    }

    /**
     * Smarter way to get localhost than InetAddress.getLocalHost.  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037
     */
    private static InetAddress getLocalHost() throws UnknownHostException, SocketException {
        // Windows Vista returns the IPv6 InetAddress using this method, which is not
        // particularly useful as it has no name or useful address, just "0:0:0:0:0:0:0:1".
        // That is why windows should be treated differently to linux/unix and use the
        // default way of getting the localhost.
        String osName = System.getProperty("os.name");
        if (osName != null && osName.toLowerCase().contains("windows")) {
            return InetAddress.getLocalHost();
        }

        InetAddress lch = null;
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();

        while (e.hasMoreElements()) {
            NetworkInterface i = e.nextElement();

            Enumeration<InetAddress> ie = i.getInetAddresses();
            if (!ie.hasMoreElements()) {
                break;
            }
            lch = ie.nextElement();
            if (!lch.isLoopbackAddress()) break;
        }
        return lch == null ? null : lch;
    }


}